//
//  AppDelegate.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/4/10.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "AppDelegate.h"
#import "ANTabBarController.h"
#import "ANNavigationController.h"
#import "ANLoginController.h"
#import "WXApiManager.h"
#import "UIViewController+Kit.h"
#import <Bugly/Bugly.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import <AdSupport/AdSupport.h>

#import "ANIMController.h"

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

static NSString * const appKey = @"678495b782db14ad93ec3702";

@interface AppDelegate ()

@property (nonatomic, strong) NSDictionary *message;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = kColorF2F2F2;
    self.window.rootViewController = [[ANTabBarController alloc] init];
    SDWebImageDownloader *downloader = [SDWebImageManager sharedManager].imageDownloader;
    if ([UserUtils shared].session.length > 0) {
        [downloader setValue:[NSString stringWithFormat:@"JSESSIONID=%@",UserUtils.shared.session] forHTTPHeaderField:@"Cookie"];
    }
    [self.window makeKeyAndVisible];
    [self keyboardManager];
    
    [WXApi startLogByLevel:WXLogLevelNormal logBlock:^(NSString *log) {
        NSLog(@"log : %@", log);
    }];
    //向微信注册,发起支付必须注册
    [WXApi registerApp:@"wx0ae6315ccfa9c1c4" enableMTA:YES];
    
    [Bugly startWithAppId:@"b17df74071"];
    [Bugly setUserIdentifier:UserUtils.shared.telString];
    
    //Required
    //notice: 3.0.0 及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        // Fallback on earlier versions
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
    }
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义 categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Optional
    // 获取 IDFA
    // 如需使用 IDFA 功能请添加此代码并在初始化方法的 advertisingIdentifier 参数中填写对应值
//    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5 版本的 SDK 新增的注册方法，改成可上报 IDFA，如果没有使用 IDFA 直接传 nil
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:@"App Store"
                 apsForProduction:1
            advertisingIdentifier:nil];
    
    if (UserUtils.shared.isLogin) {
        [JPUSHService setAlias:UserUtils.shared.vipId completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            NSLog(@"iResCode:%ld;iAlias:%@",(long)iResCode,iAlias);
        } seq:8898];
    }
    // 添加监听极光自定义消息
    [self addJPCustomNotification];
    // 本地通知内容获取：
    NSDictionary *localNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey];
    
    [self requsetControl];
    
    return YES;
}

/**
 添加监听极光自定义消息
 */
- (void)addJPCustomNotification
{
    // 极光自定义消息
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

/**
 移除监听极光自定义消息
 */
- (void)removeJPCustomNotification
{
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter removeObserver:self name:kJPFNetworkDidReceiveMessageNotification object:nil];
}


/*
 {"chatRecordId":37,"content":"19","createTime":1561207241115,"receiver":"8a8083df6a1c8ae8016a1cbfd84d000e","sender":"8a8083df6a39c435016a39ede5070006","state":0}
 */
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *message = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    // 为聊天消息
    if ([message.allKeys containsObject:@"pushType"] && [message[@"pushType"] intValue] == 2) {
        // 如果当前页面是聊天页面，就不发本地通知
        UIViewController *topVc = [UIViewController currentTopViewController];
        if (![topVc isKindOfClass:[ANIMController class]]) {
            [self addNotification:message];
        }
    }
//    NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
//    NSDictionary *extras = [userInfo valueForKey:@"extras"];
//    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的 Extras 附加字段，key 是自己定义的
    
}

- (void)addNotification:(NSDictionary *)message {
    self.message = message;
    JPushNotificationContent *content = [[JPushNotificationContent alloc] init];

//    if ([message[@"messageType"] intValue] == 1) {// 文字
//        content.body = [NSString stringWithFormat:@"%@",message[@"content"]];
//    }
//    if ([message[@"messageType"] intValue] == 2) {// 图片
////        content.body = [NSString stringWithFormat:@"%@",message[@"filePath"]];
//        content.body = @"[图片]";
//    }
    content.body = [NSString stringWithFormat:@"%@",message[@"content"]];
    content.badge = @1;
    content.categoryIdentifier = [NSString stringWithFormat:@"%@",message[@"sender"]];
    
    // 5s 后提醒 iOS 10 以上支持
    JPushNotificationTrigger *trigger1 = [[JPushNotificationTrigger alloc] init];
    trigger1.timeInterval = 1;
    
    //5s 后提醒，iOS 10 以下支持
    JPushNotificationTrigger *trigger2 = [[JPushNotificationTrigger alloc] init];
    trigger2.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
    
    JPushNotificationRequest *request = [[JPushNotificationRequest alloc] init];
    request.requestIdentifier = @"message";
    request.content = content;
    request.trigger = trigger1;
    request.completionHandler = ^(id result) {
        NSLog(@"结果返回：%@", result);
    };
    [JPUSHService addNotification:request];
}

- (void)keyboardManager
{
    [IQKeyboardManager sharedManager].shouldToolbarUsesTextFieldTintColor = YES;
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = @"完成";
    [IQKeyboardManager sharedManager].previousNextDisplayMode = IQPreviousNextDisplayModeAlwaysHide;
}

- (void)requsetControl
{
    [URLManager.shareManager getUrlStr:Api_App_Control parameters:nil success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                NSNumber *data = responseObj[@"data"];
                UserUtils.shared.showVip = data.boolValue;
            }
            else {
                UserUtils.shared.showVip = NO;
            }
        }
        else {
            UserUtils.shared.showVip = NO;
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        UserUtils.shared.showVip = NO;
    }];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark- JPUSHRegisterDelegate

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
    }else{
        //从通知设置界面进入应用
    }
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    if (![notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"收到的是本地通知");
    }
    else {
        NSLog(@"收到的是远程通知");
    }
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support  点击通知执行这个方法
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    
    if (![response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"收到的是本地通知");
        NSString *identifier = response.notification.request.identifier;
        if ([identifier isEqualToString:@"message"]) {// 点击的本地通知是聊天消息
            UIViewController *topVc = [UIViewController currentTopViewController];
            if (![topVc isKindOfClass:[ANIMController class]]) {
                NSString *sender = self.message[@"sender"];
                ANIMController *vc = [[ANIMController alloc] init];
                vc.orgId = sender;
                if ([self.message[@"messageSource"] intValue] == 2) {
                    vc.title = @"客服";
                }
                else {
                    vc.title = self.message[@"senderName"] ;
                }
                [topVc.navigationController pushViewController:vc animated:YES];
            }
        }
    }
    else {
        NSLog(@"收到的是远程通知");
        NSDictionary * userInfo = response.notification.request.content.userInfo;
        [JPUSHService handleRemoteNotification:userInfo];
    }
    // Required
    
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
}

@end
